<?php

namespace app\controller\v1;

use app\BaseController;
use app\model\OrderModel;
use app\model\OutsourcingOrderModel;
use app\model\VendorsModel;
use app\validate\VendorsAppValidate;
use think\App;
use think\facade\Db;
use think\facade\Request;

//该类只为  外协的app 服务
class VendorsApp extends BaseController
{
    public $params = [];

    protected $user;

    public function __construct(App $app)
    {
        parent::__construct($app);
        // 获取当前请求的方法名
        $action = Request::action();
        // 如果不是登录方法，则进行token检测
        $this->params = input('post.');
    }


    /**
     * Notes: token 检测方法
     * User: chenLei
     * Date: 11/3/25 10:32:52
     * @return array|mixed|Db|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkToken()
    {
        $token = Request::header('Authorization');
        if (empty($token)) {
            return ['code' => 401, 'msg' => '登录信息丢失，请重新登录'];
        }
        $token = str_replace('Bearer ', '', $token);
        // 从tokens表查询token信息
        $tokenInfo = Db::name('vendors_tokens')
            ->where('token', $token)
            ->where('status', 1)
            ->find();
        if (empty($tokenInfo)) {
            return ['code' => 401, 'msg' => '身份令牌失效，请重新登录'];
        }
        if ($tokenInfo['expires_at'] && strtotime($tokenInfo['expires_at']) < time()) {
            // 标记token为已失效
            Db::name('vendors_tokens')
                ->where('id', $tokenInfo['id'])
                ->update(['status' => 2]);
            return ['code' => 401, 'msg' => '登录已过期，请重新登录'];
        }
        //更新token信息
        $newExpiresAt = date('Y-m-d H:i:s', time() + 48 * 3600);
        Db::name('vendors_tokens')
            ->where('id', $tokenInfo['id'])
            ->update([
                'last_active_time' => date('Y-m-d H:i:s'),
                'expires_at' => $newExpiresAt
            ]);

        $user = Db::name('vendors')
            ->where('id', $tokenInfo['user_id'])
            ->where('status', 200)
            ->find();

        if (!$user) {
            return ['code' => 401, 'msg' => '用户不存在或已禁用'];
        }

        return $user;
    }

    /**
     * Notes: 登录
     * User: chenLei
     * Date: 11/3/25 10:20:38
     * @return \think\response\Json
     */
    public function login()
    {

        $validate = new VendorsAppValidate();
        if (!$validate->scene('login')->check($this->params)) return $this->errorJson($validate->getError());

        $vendorsModel = new VendorsModel();
        $res = $vendorsModel->login($this->params);
        if ($res === false) {
            return $this->errorJson($vendorsModel->getError());
        }

        return $this->successJson('ok', $res);
    }


    /**
     * Notes: 更新密码
     * User: chenLei
     * Date: 11/3/25 10:59:19
     * @return \think\response\Json
     */
    public function changePassword()
    {

        $res = $this->checkToken();
        if (!empty($res['code']) && $res['code'] == 401) {
            return $this->errorJson($res['msg'], [], $res['code']);
        }


        $validate = new VendorsAppValidate();
        if (!$validate->scene('changePassword')->check($this->params)) return $this->errorJson($validate->getError());

        $vendorsModel = new VendorsModel();
        $this->params['user_id'] = $res['id'];
        $res = $vendorsModel->changePassword($this->params);
        if ($res === false) {
            return $this->errorJson($vendorsModel->getError());
        }

        return $this->successJson('ok', $res);
    }


    /**
     * Notes: 外协详情
     * User: chenLei
     * Date: 11/3/25 11:23:13
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info()
    {
        $res = $this->checkToken();
        if (!empty($res['code']) && $res['code'] == 401) {
            return $this->errorJson($res['msg'], [], $res['code']);
        }

        $vendorsModel = new VendorsModel();
        $this->params['user_id'] = $res['id'];
        $res = $vendorsModel->info($this->params);
        if ($res === false) {
            return $this->errorJson($vendorsModel->getError());
        }

        return $this->successJson('ok', $res);

    }


    /**
     * Notes: 退出登录
     * User: chenLei
     * Date: 11/3/25 11:34:18
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function logout()
    {
        $res = $this->checkToken();
        if (!empty($res['code']) && $res['code'] == 401) {
            return $this->errorJson($res['msg'], [], $res['code']);
        }

        $token = Request::header('Authorization');
        $token = str_replace('Bearer ', '', $token);

        // 将token标记为已失效
        Db::name('vendors_tokens')
            ->where('token', $token)
            ->where('user_id', $res['id'])
            ->update(['status' => 2]);

        return $this->successJson('退出登录成功');
    }


    /**
     * Notes: 外协订单统计
     * User: chenLei
     * Date: 11/3/25 11:42:53
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderStatistics()
    {
        $res = $this->checkToken();
        if (!empty($res['code']) && $res['code'] == 401) {
            return $this->errorJson($res['msg'], [], $res['code']);
        }

        $vendorsModel = new VendorsModel();
        $this->params['user_id'] = $res['id'];
        $res = $vendorsModel->orderStatistics($this->params);

        return $this->successJson('ok', $res);
    }


    /**
     * Notes: 订单列表
     * User: chenLei
     * Date: 11/3/25 14:05:06
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderList()
    {
        $res = $this->checkToken();
        if (!empty($res['code']) && $res['code'] == 401) {
            return $this->errorJson($res['msg'], [], $res['code']);
        }

        $vendorsModel = new VendorsModel();
        $this->params['user_id'] = $res['id'];
        $res = $vendorsModel->orderList($this->params);

        return $this->successJson('ok', $res);

    }


    /**
     * Notes: 订单详情
     * User: chenLei
     * Date: 11/3/25 14:12:26
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderInfo()
    {
        $res = $this->checkToken();
        if (!empty($res['code']) && $res['code'] == 401) {
            return $this->errorJson($res['msg'], [], $res['code']);
        }

        $validate = new VendorsAppValidate();
        if (!$validate->scene('orderInfo')->check($this->params)) return $this->errorJson($validate->getError());

        $orderModel = new OrderModel();
        $res = $orderModel->info($this->params);
        if ($res === false) {
            return $this->errorJson($orderModel->getError());
        }


        return $this->successJson('ok', $res);
    }


    /**
     * Notes: 提交订单开始生产
     * User: chenLei
     * Date: 11/3/25 14:16:46
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function submitProductionExecution()
    {
        $res = $this->checkToken();
        if (!empty($res['code']) && $res['code'] == 401) {
            return $this->errorJson($res['msg'], [], $res['code']);
        }

        $validate = new VendorsAppValidate();
        if (!$validate->scene('submitProductionExecution')->check($this->params)) return $this->errorJson($validate->getError());

        $orderModel = new OutsourcingOrderModel();
        $res = $orderModel->submitProductionExecution($this->params);
        if ($res === false) {
            return $this->errorJson($orderModel->getError());
        }
        return $this->successJson('ok', $res);
    }


    /**
     * Notes: 确认订单生产完成
     * User: chenLei
     * Date: 11/3/25 14:16:58
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function productionCompleted()
    {
        $res = $this->checkToken();
        if (!empty($res['code']) && $res['code'] == 401) {
            return $this->errorJson($res['msg'], [], $res['code']);
        }

        $validate = new VendorsAppValidate();
        if (!$validate->scene('productionCompleted')->check($this->params)) return $this->errorJson($validate->getError());

        $orderModel = new OutsourcingOrderModel();
        $res = $orderModel->productionCompleted($this->params);
        if ($res === false) {
            return $this->errorJson($orderModel->getError());
        }
        return $this->successJson('ok', $res);
    }

    /**
     * Notes: 确认订单交付
     * User: chenLei
     * Date: 11/3/25 14:17:07
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function wxConfirmDelivery()
    {
        $res = $this->checkToken();
        if (!empty($res['code']) && $res['code'] == 401) {
            return $this->errorJson($res['msg'], [], $res['code']);
        }

        $validate = new VendorsAppValidate();
        if (!$validate->scene('wxConfirmDelivery')->check($this->params)) return $this->errorJson($validate->getError());

        $orderModel = new OutsourcingOrderModel();
        $res = $orderModel->wxConfirmDelivery($this->params);
        if ($res === false) {
            return $this->errorJson($orderModel->getError());
        }
        return $this->successJson('ok', $res);
    }


    /**
     * Notes: 外协物料订单
     * User: chenLei
     * Date: 11/14/25 13:11:28
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function outsourcingOrderList()
    {
        $res = $this->checkToken();
        if (!empty($res['code']) && $res['code'] == 401) {
            return $this->errorJson($res['msg'], [], $res['code']);
        }
        $this->params['user_id'] = $res['id'];
        $model = new OutsourcingOrderModel();
        $res = $model->outsourcingOrderList($this->params);
        return $this->successJson('ok', $res);
    }


    /**
     * Notes: 订单详情
     * User: chenLei
     * Date: 11/14/25 13:21:03
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function outsourcingOrderInfo()
    {
        $res = $this->checkToken();
        if (!empty($res['code']) && $res['code'] == 401) {
            return $this->errorJson($res['msg'], [], $res['code']);
        }
        if (empty($this->params['id'])) {
            return $this->errorJson('参数错误');
        }
        $model = new OutsourcingOrderModel();
        $res = $model->outsourcingOrderInfo($this->params);
        if ($res === false) {
            return $this->errorJson($model->getError());
        }
        return $this->successJson('ok', $res);

    }

    /**
     * Notes: App 配置
     * User: chenLei
     * Date: 11/16/25 15:59:12
     * @return \think\response\Json
     */

    public function appConfig()
    {
        $version = '1';
        $url = 'https://tyhoa.ytxltwy.cn/tyapp.apk';

        $data = [
            'version' => $version,
            'url' => $url
        ];

        return $this->successJson('ok', $data);
    }
}